import { getUserInfo } from '@/api/user'
import {
  setStorageToken,
  getStorageToken,
  removeStorageToken
} from '@/utils/storage'
import { Toast } from 'vant'

export default {
  namespaced: true,
  state: {
    // token: JSON.parse(localStorage.getItem('hm-news-token')) || {}
    token: getStorageToken('hm-news-token') || {},
    userInfo: {}
  },
  mutations: {
    setToken(state, payload) {
      state.token = payload
      // 把payload保存到localStorage中
      // localStorage中如果要存储复杂类型的数据，需要先转成JSON字符串进行存储。
      // localStorage.setItem('hm-news-token', JSON.stringify(payload))
      setStorageToken(payload)
    },
    // 把本地存储tken删除
    removeToken(state) {
      state.token = {}
      removeStorageToken()
    },
    // 把个人信息数据存vuex中
    setUserInfo(state, payload) {
      state.userInfo = payload
    }
  },
  actions: {
    async Actions_getUserInfo(context) {
      try {
        const res = await getUserInfo()
        context.commit('setUserInfo', res.data)
      } catch {
        Toast('获取信息失败')
      }
    }
  }
}
